package org.example.secondkill.service.impl;

import org.example.secondkill.dao.GoodsDao;
import org.example.secondkill.domain.Goods;
import org.example.secondkill.domain.vo.GoodsDetailVO;
import org.example.secondkill.redis.GoodsKey;
import org.example.secondkill.redis.RedisService;
import org.example.secondkill.response.ResultCode;
import org.example.secondkill.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsService implements IGoodsService {
    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private RedisService redisService;

    public Goods getGoodsByGoodsId(long goodsId) {
        // 先查看缓存
        Goods goods = redisService.get(
                GoodsKey.getGoodsList,
                "" + goodsId,
                Goods.class
        );
        if (goods != null) {
            return goods;
        } else {
            goods = goodsDao.selectGoodsVOByGoodsId(goodsId);
            redisService.set(
                    GoodsKey.getGoodsList,
                    "" + goods.getId(),
                    goods
            );
            return goods;
        }
    }

    @Override
    public GoodsDetailVO getGoodsDetailVOByGoodsId(long goodsId) {
        Goods goods = getGoodsByGoodsId(goodsId);
        long startTime = goods.getStartDate().getTime();
        long endTime = goods.getEndDate().getTime();
        long now = System.currentTimeMillis();

        ResultCode resultCode;
        int remainTime;  // 距离秒杀开始的剩余时间（单位：s）
        // 秒杀还未开始
        if (now < startTime) {
            resultCode = ResultCode.KILL_NOT_START;
            remainTime = (int) (startTime - now) / 1000;
        } else if (now > endTime) {
            // 秒杀已经结束
            resultCode = ResultCode.KILL_END;
            remainTime = -1;
        } else {
            resultCode = ResultCode.KILL_ONGOING;
            remainTime = 0;
        }
        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        goodsDetailVO.setGoods(goods);
        goodsDetailVO.setRemainTime(remainTime);
        goodsDetailVO.setResultCode(resultCode);
        return goodsDetailVO;
    }

    @Override
    public List<Goods> getAllGoods() {
        return goodsDao.selectAllGoods();
    }

    /**
     * 重置商品
     */
    public void updateGoods(List<Goods> goodsList) {
        for (Goods goods : goodsList) {
            goodsDao.updateStock(goods);
        }
    }
}
